`timescale 1ns/1ps
module six_0111_top;
    reg X,clock,reset;
    wire flag;

    always # 1 clock = ~clock;
    initial begin
        reset = 0;
        clock = 0;
        X = 0;
        # 2 reset =1;
        # 2 reset =0;
        # 2 X = 0;  # 2 X = 1;  # 2 X = 1; # 2 X = 1;
        # 2 X = 0;  # 2 X = 1;  # 2 X = 1; # 2 X = 1;
        # 2 X = 0;  # 2 X = 1;  # 2 X = 1; # 2 X = 1;
        # 2 X = 0;  # 2 X = 1;  # 2 X = 1; # 2 X = 1;
        # 2 X = 0;  # 2 X = 1;  # 2 X = 1; # 2 X = 1;
        # 2 X = 0;  # 2 X = 1;  # 2 X = 1; # 2 X = 1;
        # 8 reset = 1; # 2 reset=0;

        # 2 X = 0;  # 2 X = 1;  # 2 X = 1; # 2 X = 1;
        # 2 X = 0;  # 2 X = 1;  # 2 X = 1; # 2 X = 1;
        # 2 X = 0;  # 2 X = 1;  # 2 X = 1; # 2 X = 1;
        # 2 X = 0;  # 2 X = 1;  # 2 X = 1; # 2 X = 1;
        # 2 X = 0;  # 2 X = 1;  # 2 X = 1; # 2 X = 1;
        # 2 X = 0;  # 2 X = 1;  # 2 X = 1; # 2 X = 1;
        # 2 X = 0;  # 2 X = 1;  # 2 X = 1; # 2 X = 1;
        # 2 X = 0;  # 2 X = 1;  # 2 X = 1; # 2 X = 1;
        # 4 $stop;
    end
    six_0111 s0(flag,X,clock,reset);
	initial
	begin
    	$dumpfile("test.vcd");
    	$dumpvars(0, s0);
 	end
endmodule


module six_0111(flag,X,clock,reset);
    input X,clock,reset;
    output flag;
    wire Z;
    reg [2:0]count;
    reg [2:0]t1,t2;//to store count and detect count from "5" to "6".
    assign flag = (t1==5'b110 & t2 == 5'b101)?1:0;
    always @(posedge clock or posedge reset)
        if(reset)begin
            t1 <= 0;
            t2 <= 0;
        end
        else begin
            t1 <= count;
            t2 <= t1;
        end 

    always @(posedge clock or posedge reset)
        if(reset)begin
            count <=3'b000;
        end
    else if(count == 3'b110)
        count <= 3'b110;
    else if(Z==1) begin
        count <= count+3'b001;        
    end 

    serial_bit sb(Z,X,clock,reset);
    
endmodule

module serial_bit(Z,X,clock,reset);
    input X,clock,reset;
    output Z;
    reg [2:0]state,next;
    parameter RESET=3'd0,S0=3'd1,S1=3'd2,S2=3'd3,S3=3'd4;
    assign Z = (state==S3)?1:0;
    always @(posedge clock or posedge reset)
        if(reset)
            state <= RESET;
        else
            state <= next;

    always @(*)
        case(state)
            RESET:next = (X==1)? RESET:S0;
            S0: next = (X==1)?S1:S0;
            S1: next = (X==1)?S2:S0;
            S2: next = (X==1)?S3:S0;
            S3: next = (X==1)?RESET:S0;
            default:next = RESET;
        endcase
endmodule
